package com.highcom.servlet;

import com.highcom.bean.AdminInfo;
import com.highcom.dao.AdminInfoDao;
import com.highcom.dao.impl.AdminInfoDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 王卓逸
 * @program TODO
 * @description TODO
 * @create 2019-10-11
 */
@WebServlet("/admin.do")
public class AdminServlet extends HttpServlet {

    private AdminInfoDao adminInfoDao = new AdminInfoDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String flag = req.getParameter("flag");
        switch (flag) {
            case "checkName":
                this.checkName(req, resp);
                break;
            case "addAdmin":
                break;
            case "manage":
                break;
            case "delAdmins":
                break;
            default:
                break;
        }
    }

    private void checkName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String adminName = req.getParameter("adminName");
        AdminInfo adminInfo = adminInfoDao.selectByAdminName(adminName);
        if (null != adminInfo) {
            resp.getWriter().println(0);
        } else {
            resp.getWriter().println(1);
        }
    }

    private void addAdmin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String adminName = req.getParameter("adminName");
        String password = req.getParameter("password");
        String note = req.getParameter("note");
        AdminInfo adminInfo = new AdminInfo();
        adminInfo.setAdminName(adminName);
        adminInfo.setPassword(password);
        adminInfo.setNote(note);
        adminInfo.setState(1);
        if (adminInfoDao.insert(adminInfo) != 0) {
            req.setAttribute("msg", "管理员添加成功");
            req.getRequestDispatcher("admin/AdminAdd.jsp").forward(req, resp);
        }
    }
}
